package com.dds.system.service.sys.impl;

import java.util.List;
import java.util.Map;

import com.dds.common.utils.DateUtils;
import org.apache.ibatis.annotations.SelectKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dds.system.mapper.sys.SysDicMapper;
import com.dds.system.domain.sys.SysDic;
import com.dds.system.service.sys.ISysDicService;

/**
 * 数据分类Service业务层处理
 *
 * @author gaolianjie
 * @date 2021-04-12
 */
@Service
public class SysDicServiceImpl implements ISysDicService {
    @Autowired
    private SysDicMapper sysDicMapper;

    /**
     * 查询数据分类
     *
     * @param dicId 数据分类ID
     * @return 数据分类
     */
    @Override
    public SysDic selectSysDicById(Long dicId) {
        return sysDicMapper.selectSysDicById(dicId);
    }

    /**
     * 查询数据分类列表
     *
     * @return 数据分类
     */
    @Override
    public List<Map<String, Object>> selectSysDicList(Long categoryId) {
        return sysDicMapper.selectSysDicList(categoryId);
    }

    /**
     * 新增数据分类
     *
     * @param sysDic 数据分类
     * @return 结果
     */
    @Override
    public int insertSysDic(SysDic sysDic) {
        sysDicMapper.insertSysDic(sysDic);

        SysDic newDic = selectSysDicById(sysDic.getDicId());

        String level = "1";

        if (newDic.getDicPid() != 0) {
            level = getLevel(sysDic.getDicPid(), 2);
        }

        newDic.setLevel(level);
        newDic.setDicCode(newDic.getCategoryId() + "_" + level + "_" + newDic.getDicId());
        return updateSysDic(newDic);
    }

    /**
     * 修改数据分类
     *
     * @param sysDic 数据分类
     * @return 结果
     */
    @Override
    public int updateSysDic(SysDic sysDic) {
        sysDic.setUpdateTime(DateUtils.getNowDate());

        return sysDicMapper.updateSysDic(sysDic);
    }

    /**
     * @param pid
     * @param level
     * @return
     */
    private String getLevel(Long pid, int level) {
        SysDic sysDic = selectSysDicById(pid);

        if (sysDic != null) {
            if (sysDic.getDicPid() != 0) {
                ++level;
                return getLevel(sysDic.getDicPid(), level);
            }
        }
        System.out.println("level" + level);
        return String.valueOf(level);
    }

    /**
     * 批量删除数据分类
     *
     * @param dicIds 需要删除的数据分类ID
     * @return 结果
     */
    @Override
    public int deleteSysDicByIds(Long[] dicIds) {
        return sysDicMapper.deleteSysDicByIds(dicIds);
    }

    /**
     * 删除数据分类信息
     *
     * @param dicId 数据分类ID
     * @return 结果
     */
    @Override
    public int deleteSysDicById(Long dicId) {
        return sysDicMapper.deleteSysDicById(dicId);
    }

    @Override
    public boolean selectSysDicByPid(Long pid) {
        return sysDicMapper.selectSysDicByPid(pid) > 0;
    }
}
